package com.ctyon.watchmanager;


import android.util.Log;

import com.ctyon.watchmanager.model.db.AppDatabase;
import com.ctyon.watchmanager.model.db.entity.ChatMessageEntity;
import com.ctyon.watchmanager.model.db.entity.LocationEntity;
import com.ctyon.watchmanager.model.db.entity.LoginHistoryEntity;

import java.util.List;

import androidx.lifecycle.LiveData;

/**
 * Repository handling the work with products and comments.
 */
public class DataRepository {

    private static DataRepository sInstance;

    private final AppDatabase mDatabase;

    private DataRepository(final AppDatabase database) {
        mDatabase = database;
    }

    public static DataRepository getInstance(final AppDatabase database) {
        if (sInstance == null) {
            synchronized (DataRepository.class) {
                if (sInstance == null) {
                    sInstance = new DataRepository(database);
                }
            }
        }
        return sInstance;
    }

    /**
     * Get the list of products from the database and get notified when the data changes.
     */
    public LiveData<List<LoginHistoryEntity>> loadLoginHistory() {
        return mDatabase.loginHistoryDao().loadLoinHistory();
    }

    public List<ChatMessageEntity> loadChatHistory() {
        return mDatabase.chatHistoryDao().loadChatHistory();
    }

    public List<LocationEntity> loadLocations() {
        return mDatabase.locationEntityDao().loadLocationHistory();
    }

    public String findLastLocationTime() {
        return mDatabase.locationEntityDao().findLastTime();
    }

    public Long findLastChatTime() {
        return mDatabase.chatHistoryDao().findLastTime();
    }

    public void insertHistory(final LoginHistoryEntity historyEntity) {
        mDatabase.runInTransaction(() -> {
            LoginHistoryEntity historyEntityE = mDatabase.loginHistoryDao().selectLoginHistoryByManagerId(historyEntity.getUserId());
            if (null != historyEntityE){
                if (!historyEntityE.equals(historyEntity)){
                    mDatabase.loginHistoryDao().updateHistory(historyEntity);
                }
            }else {
                mDatabase.loginHistoryDao().insertHistory(historyEntity);
            }
        });
    }

    public void insertChatMessage(final ChatMessageEntity entity) {
        mDatabase.runInTransaction(() -> {
            Log.d("insertChatMessage : ", "insertChat : " + entity.toString());
            Long result = mDatabase.chatHistoryDao().insertChat(entity);
            Log.d("insertChatMessage : ", "" + result);
        });
    }

    public void insertLocations(final List<LocationEntity> locations) {
        mDatabase.runInTransaction(() -> {
            mDatabase.locationEntityDao().insertAll(locations);
        });
    }

}
